import router from 'umi/router';
import { message } from 'antd';
import {
  getAllDevices,
  getCache,
  addCache,
  updateCache,
  freshConfig

} from './services';

export default {
  namespace: 'cacheConfig',
  state: {
    allDevices: [],
    allDomainGroup:[],
    loading: false,
    confLoading: false,
    list: [],
    pageSize: 10,
    pageNum: 1,
    cache: {}
  },

  effects: {
    /**
     * 缓存
     */

    *getAllDevices({ payload,callback }, { call, put }) {
      try {
        const res = yield call(getAllDevices, payload);
        callback(res.data[0]);
        yield put({
          type: 'save',
          payload: {
            allDevices: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      }
    },
    *getCache({ payload }, { call, put }) {
      try {
        yield put({
          type: 'changeConfLoading',
          payload: true,
        });
        const res = yield call(getCache, payload);
        yield put({
          type: 'save',
          payload: {
            cache: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({
          type: 'changeConfLoading',
          payload: false,
        });
      }
    },

    *freshConfig({ payload, callback }, { call, put, select }) {
      try {
        yield call(freshConfig, payload);
        message.info("启用成功")
      } catch (e) {
        message.error(e.message);
      }
    },


    *addCache({ payload, callback }, { call, put }) {
      try {
        yield call(addCache, payload);
        message.info('配置成功');
        callback();
      } catch (e) {
        message.error(e.message);
      }
    },

    *updateCache({ payload, callback }, { call, put }) {
      try {
        yield call(updateCache, payload);
        message.info('修改成功');
        callback();
      } catch (e) {
        message.error(e.message);
      }
    },

    *getAllDevices({ payload,callback }, { call, put }) {
      try { 
        const res = yield call(getAllDevices, payload);
        if(res.data.length>0) {
          callback(res.data[0]);
        }
        yield put({
          type: 'save',
          payload: {
            allDevices: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      }
    },
  
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },

    changeConfLoading(state, { payload }) {
      return {
        ...state,
        confLoading: payload,
      };
    },

    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
